package pl.edu.mimuw.irs.rcp.controller.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

import pl.edu.mimuw.irs.core.model.design.net.IRSRequirement;
import pl.edu.mimuw.irs.core.model.design.resource.Roles;
import pl.edu.mimuw.irs.rcp.controller.editor.requirements.RequirementsEditor;
import pl.edu.mimuw.irs.rcp.controller.editor.requirements.RequirementsEditorInput;
import pl.edu.mimuw.irs.rcp.controller.editor.workflow.IRSWorkflowEditor;
import pl.edu.mimuw.irs.rcp.controller.editor.workflow.part.IRSRequirementEditPart;
import pl.edu.mimuw.irs.rcp.util.Logger;
import pl.edu.mimuw.irs.rcp.util.MessageCode;

public class EditRequirementsHandler extends AbstractHandler {


	// *** Attributes

	// *** Methods
	
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// Get the editor
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		IWorkbenchPage page = window.getActivePage();
		IEditorPart editor = page.getActiveEditor();
		if (!(editor instanceof IRSWorkflowEditor)) return null;
		IRSWorkflowEditor workflowEditor = (IRSWorkflowEditor) editor;
		Roles roles = workflowEditor.getModel().getRoles();
		// Get the selection
		ISelection selection = workflowEditor.getSite().getSelectionProvider()
				.getSelection();
		
		if (selection != null && selection instanceof IStructuredSelection) {
			IStructuredSelection structuredSelection = (IStructuredSelection) selection;
			Object obj = structuredSelection.getFirstElement();
			// If we had a selection let's open the editor
			if (obj != null && (obj instanceof IRSRequirementEditPart)) {
				IRSRequirementEditPart part = (IRSRequirementEditPart) obj;
				IRSRequirement requirement = (IRSRequirement)part.getIRSNode();
				RequirementsEditorInput input = new RequirementsEditorInput(requirement, roles);
				try {
					page.openEditor(input, RequirementsEditor.ID);
				} catch (PartInitException e) {
					Logger.handle(MessageCode.EDITOR_OPEN_PROBLEM, e, RequirementsEditor.ID);
				}
			}
		}

		return null;
	}
}
